package com.crpc.core.compress.impl;

import com.crpc.common.crpcEnum.CrpcExceptionEnums;
import com.crpc.common.exception.CrpcException;
import com.crpc.core.compress.Compressor;
import lombok.extern.slf4j.Slf4j;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;

import java.util.Arrays;


/**
 * @author wzy
 * @version 1.0
 * @description:
 * @date 2023/9/30 9:09
 */
@Slf4j
public class LZ4Compressor implements Compressor {
    @Override
    public byte[] compress(byte[] bytes) {

        // 获取LZ4压缩器
        LZ4Factory factory = LZ4Factory.fastestInstance();
        net.jpountz.lz4.LZ4Compressor compressor = factory.fastCompressor();
        // 为压缩数据分配缓冲区
        int maxCompressedLength = compressor.maxCompressedLength(bytes.length);
        byte[] compressedData = new byte[maxCompressedLength];
        try {
            int compressedLength = compressor.compress(bytes, 0, bytes.length, compressedData, 0, maxCompressedLength);
            log.info("===============使用LZ4进行压缩===============");
            return Arrays.copyOf(compressedData, compressedLength);
        } catch (Exception e) {
            log.error("===============LZ4压缩时发生异常===============");
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.COMPRESS_ERROR);
        }
    }

    @Override
    public byte[] decompress(byte[] bytes) {
        LZ4Factory factory = LZ4Factory.fastestInstance();
        LZ4FastDecompressor decompressor = factory.fastDecompressor();
        int originalLength = bytes.length;
        // 为解压数据分配缓冲区
        byte[] decompressedData = new byte[originalLength];
        try {
            decompressor.decompress(bytes, 0, decompressedData, 0, originalLength);
            log.info("===============使用LZ4进行解压缩===============");
            return decompressedData;

        } catch (Exception e) {
            log.error("===============LZ4解压缩时发生异常===============");
            e.printStackTrace();
            throw new CrpcException(CrpcExceptionEnums.COMPRESS_ERROR);
        }
    }
}
